package jcsy3;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Main {
    //BlockingQueue 是线程安全的，并且在调用 put，take 方法时会阻塞线程，
    //超过指定容量时，用put时会进行阻塞，没有元素时，利用take会进行阻塞
    private static Main main1 = new Main();
    public static final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1);
    static int i = 0;

    public static void main(String[] args) {
        Producer producer = new Producer();
        Consumer consumer = new Consumer();
        producer.start();
        consumer.start();
        synchronized (main1) {
            try {
                System.out.println("主线程进入等待");
                main1.wait();
                System.out.println("我是主线程我被Consumer唤醒了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    static class Producer extends Thread {

        int n = 10;

        public void run() {
            while (i < 10) {
                try {
                    queue.put(i);//队列满的话，put会阻塞当前线程
                    System.out.println("生产元素：" + i++);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Consumer extends Thread {

        int n = 10;

        public void run() {
            while (i<10) {
                try {
                    int res = queue.take();//队列为空的话，会阻塞线程
                    System.out.println("消费元素：" + res);
                    Thread.sleep(1000);
                    if (res == 9) {
                        System.out.println("我要唤醒主线程啦！");
                        synchronized (main1){
                            main1.notify();
                        }

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}